package com.fuda.trade

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.net.wifi.WifiManager
import android.util.Log
import androidx.core.content.getSystemService
import java.net.InetAddress

object Constants {
    const val BROADCAST_QUERY_REQUEST  = "com.fuda.trade.QUERY"
    const val BROADCAST_QUERY_RESPONSE = "com.fuda.trade.QUERY_"

    const val BROADCAST_COMMAND_APPROVE_REQUEST = "com.fuda.trade.COMMAND_APPROVE"
    const val BROADCAST_COMMAND_APPROVE_RESPONSE= "com.fuda.trade.COMMAND_APPROVE_"

    // 有些wifi可能关闭了tcp等，导致android-zenoh与mac-zenoh不同通信，如Timmus的wifi
    // 而我家里的和手机热点就可以，还要继续研究是不是配置问题@2024-08-02
    const  val ZENOH_CONFIG = """
    {
      "mode": "peer",
      "connect": {
        "endpoints": [
            "tcp/172.17.0.151:59592", 
            "tcp/172.17.0.151:59589",
            
            "tcp/192.168.43.62:57374",
            "tcp/192.168.43.62:57465"
        ]
      }
    }
    """
}

class IPAddressService(private val context: Context) : ConnectivityManager.NetworkCallback() {

    private var network: Network? = null
    private var ipAddress: String? = null

    fun startListening() {
        val manager = context.getSystemService<WifiManager>()
        val builder = NetworkRequest.Builder()
        val request = builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build()

        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        connectivityManager.requestNetwork(request, this)

        // Wait for the callback to set the IP address
        while (ipAddress == null) {
            Thread.sleep(100)
        }

        Log.d("IPAddress", "Device IP Address: $ipAddress")
    }

    override fun onAvailable(network: Network) {
        super.onAvailable(network)
        this.network = network
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        val linkProperties =connectivityManager.getLinkProperties(network)

        if (linkProperties != null) {
            val ipv4Addr = linkProperties.linkAddresses.firstOrNull { it.address is InetAddress && isIpv4Address(it.address) }

            if (ipv4Addr != null) {
                ipAddress = ipv4Addr.address.hostAddress
            }
        }
    }

    override fun onLost(network: Network) {
        super.onLost(network)
        this.network = null
    }

    private fun isIpv4Address(address: InetAddress): Boolean {
        return address.address.size == 4
    }
}

// Usage:
//val ipAddressService = IPAddressService(this) // Replace `this` with your activity or fragment context
//ipAddressService.startListening()